package com.thinkersre.controller;


import com.thinkersre.entity.DiscussPost;
import com.thinkersre.entity.Page;
import com.thinkersre.entity.User;
import com.thinkersre.service.DiscussPostService;
import com.thinkersre.service.LikeService;
import com.thinkersre.service.UserService;
import com.thinkersre.util.ThinkersReConstant;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

//@Api(tags = "主页")
@Controller

public class HomeController implements ThinkersReConstant {
    @Resource
    private UserService userService;
    @Resource
    private DiscussPostService discussPostService;
    @Resource
    private LikeService likeService;
//    @ApiOperation("实现主页展示功能")
    @GetMapping("/")
    public String root(){
        return "forward:/index";
    }
    @GetMapping("/index")
    public String getIndexPage(Model model, Page page,@RequestParam(name = "orderMode",defaultValue = "0") int orderMode){
        //在方法调用前，springmvc会自动实例化model和page，并将page自动注入model
        //所以在thymeleaf中page的数据可以直接访问
        //首页显示数据行数
        page.setRowsTotal(discussPostService.findDiscussPostRows(0));
        //分页路径
        page.setPath("/index?orderMode="+orderMode);

        //获取post列表
        List<DiscussPost> discussPostList = discussPostService.findDiscussPosts(0, page.getOffset(), page.getPageSize(),orderMode);
        //新建post与user的结果集容器
        List<Map<String, Object>> discussPostLists = new ArrayList<>();
        //判断discussList是否为空
        if(discussPostList != null){
            //遍历post列表并存入
            for (DiscussPost post :
                    discussPostList) {
                //临时性装配map
                Map<String,Object> map = new HashMap<>();
                //开始装入post参数
                map.put("post",post);
                //创建user实体
                User user = userService.findUserById(post.getUserId());
                //开始装入用户参数
//                map.put("user",userService.selectById(post.getUserId()));
                map.put("user",user);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount",likeCount);



                //将map传入结果集容器
                discussPostLists.add(map);
            }


        }
        //将数据传入model
        model.addAttribute("discussPosts",discussPostLists);
        model.addAttribute("orderMode",orderMode);


        return "/index";
    }

    @GetMapping("/error")
    public String getErrorPage(){
        return "/error/500";
    }

    @GetMapping("denied")
    public String getDeniedPage(){
        return "/error/404";
    }
}
